package com.jin.webvideo.exception;

import com.alibaba.fastjson.JSONObject;
import com.jin.webvideo.entity.ResultEntity;
import com.jin.webvideo.util.base.StringUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@ControllerAdvice
public class GlobalExceptionHandler {

    public static void autoSetSend(HttpServletRequest request, HttpServletResponse httpServletResponse, String path, int code, ResultEntity msg) throws ServletException, IOException {
        // ajax请求
        if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("x-requested-with"))){
            String msgStr = JSONObject.toJSONString(msg);
            httpServletResponse.setContentType("application/json;;charset=UTF-8");
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write(msgStr);
            writer.flush();
            return;
        }
        httpServletResponse.sendError(code);
        request.setAttribute("msg", msg.getMsg());
        request.getRequestDispatcher(path).forward(request, httpServletResponse);
    }
    public static void autoSend(HttpServletRequest request, HttpServletResponse response,int code, ResultEntity msg) throws ServletException, IOException {
        autoSetSend(request, response, "/error", code, msg);
    }
    public static void auto5xx(HttpServletRequest request, HttpServletResponse response, ResultEntity msg) throws ServletException, IOException {
        autoSend(request, response, 500, msg);
    }

    @ExceptionHandler(value = DataException.class)
    public void exceptionHandler(HttpServletRequest req, HttpServletResponse res, DataException e) throws ServletException, IOException {
        autoSend(req, res, 200, ResultEntity.fail(e.getMessage()));
    }
    @ExceptionHandler(value = UnavailableServiceException.class)
    public void exceptionHandler(HttpServletRequest req,HttpServletResponse response, UnavailableServiceException e) throws ServletException, IOException {
        auto5xx(req, response, ResultEntity.fail(StringUtil.isEmpty(e.getMessage())?"服务不可用， 请检查相关服务":e.getMessage()));
    }
    @ExceptionHandler(value = UnsupportedEncodingException.class)
    public void exceptionHandler(HttpServletRequest req, HttpServletResponse res, UnsupportedEncodingException e) throws ServletException, IOException {
        auto5xx(req, res, ResultEntity.fail("编码不可用， 请检查服务环境"));
    }

    @ExceptionHandler(value = ParsingFailedException.class)
    public String exceptionHandler(HttpServletRequest req, HttpServletResponse resp, ParsingFailedException e) throws ServletException, IOException {
        return "error/parsingError";
    }
}
